package com.robot.orders.service;

import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WeChatPay;
import com.robot.orders.config.WeChatPayConfig;
import com.robot.orders.handler.AbstractHandler;
import com.robot.orders.handler.HandlerContext;
import com.robot.orders.pojo.vo.OrdersRequestModel;
import com.robot.orders.pojo.vo.Payment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import util.WeChatUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wuyunbin
 */
@Service
public class PayService {

    @Value("${wechat.appid}")
    private String appId;

    @Value("${wechat.secret}")
    private String secret;

    @Autowired
    private RedisTemplate redisTemplate;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    WeChatPayConfig config = new WeChatPayConfig();
    WeChatPay weChatPay = new WeChatPay(config);
    @Autowired
    private HandlerContext handlerContext;

    public PayService() throws Exception {
    }

    public HashMap<String, String> handler(Payment payment, OrdersRequestModel ordersRequestModel) throws Exception {

        AbstractHandler handler = handlerContext.getInstance(payment.getType() + "");
        return handler.handle(payment, ordersRequestModel);
    }

    public HashMap<String, String> getConfig(String url) throws Exception {
        logger.info("url="+url);

        Map response=(Map)JSON.parse(WeChatUtil.getClientCredentialAccessToken(appId,secret));
        String accessToken=(String)response.get("access_token");
        logger.info("token="+accessToken);

        String ticket=getWeChatJsApiTicket(accessToken);
        logger.info("ticket="+accessToken);
        String nonceStr=String.valueOf(System.currentTimeMillis());

        HashMap<String, String> result = new HashMap<>(4);
        result.put("appid", config.getAppId());
        result.put("nonceStr", nonceStr);
        result.put("timestamp", nonceStr);
        result.put("signature", WeChatUtil.getJsApiTicketSignature(ticket,nonceStr,nonceStr,url));

        logger.info(result.toString());

        return result;
    }

    public String getWeChatJsApiTicket(String accessToken) {
        String jsApiTicket=(String) redisTemplate.opsForValue().get("jsapi_ticket");
        if(jsApiTicket!=null){
            logger.info("get jsApiTicket from redis jsApiTicket");
            return jsApiTicket;
        }
        String response=WeChatUtil.getWeChatJsApiTicket(accessToken);
        Map result = (Map) JSON.parse(response);
        logger.info("response="+response);
        jsApiTicket=(String) result.get("ticket");
        return jsApiTicket;
    }

}

